package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.entity.XlsUserAwardEntity;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.dao.XlsUserAwardDao;
import io.renren.dto.XlsUserAwardDTO;
import io.renren.service.XlsUserAwardService;
import io.renren.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户奖励表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-03-28
 */
@Service
public class XlsUserAwardServiceImpl extends CrudServiceImpl<XlsUserAwardDao, XlsUserAwardEntity, XlsUserAwardDTO> implements XlsUserAwardService {

    @Autowired
    private XlsUserAwardDao xlsUserAwardDao;

    @Override
    public QueryWrapper<XlsUserAwardEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<XlsUserAwardEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    /**
     * 奖励金添加
     * @param xlsUserAwardEntity
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> increaseRewardAmount(XlsUserAwardEntity xlsUserAwardEntity) {
        Map<String,Object> map=new HashMap<>();
        try{
            if (StringUtils.isNotNull(xlsUserAwardEntity)){
                if (StringUtils.isNotNull(xlsUserAwardEntity.getXlsUserId())){
                    XlsUserAwardEntity userAwardEntity = xlsUserAwardDao.selectUserAwardByUserId(xlsUserAwardEntity.getXlsUserId());
                    if (StringUtils.isNotNull(userAwardEntity)){
                        userAwardEntity.setAwardPrice(xlsUserAwardEntity.getAwardPrice().add(userAwardEntity.getAwardPrice()).setScale(2, BigDecimal.ROUND_DOWN));
                        xlsUserAwardDao.updateById(userAwardEntity);
                    }else {
                        xlsUserAwardDao.insert(xlsUserAwardEntity);
                    }
                    map.put("status",1);
                    map.put("msg","奖励添加成功");
                    return map;
                }else {
                    map.put("status",-1);
                    map.put("msg","请登录用户");
                    return map;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
            map.put("status",-1);
            map.put("msg","服务器错误");
            return map;
        }
        map.put("status",-1);
        map.put("msg","数据错误");
        return map;
    }
}